<template>
  <view class="container" :style="appThemeStyle">
    <!-- 店铺页面组件 -->
    <!-- <Page :items="items" /> -->
	<view class="top-log">
		<u-swiper :list="banner_list" :height="450" name="thumbnail" mode="none" @click="goDetails"></u-swiper>
		<!-- <image class="image" src="/static/img/banner.jpg" mode="widthFix"></image> -->
		<view class="yun-cloud">
			<image class="image-cloud" src="/static/img/cloud.png" mode="widthFix"></image>
		</view>
	</view>
	<view class="model-content-box">
		<view class="model-item" @click="goCourse">
			<image class="model-image" src="/static/img/icon1.png" mode="widthFix"></image>
			<view class="model-name">课程</view>
		</view>
		<view class="model-item" @click="goSquare">
			<image class="model-image" src="/static/img/icon2.png" mode="widthFix"></image>
			<view class="model-name">广场</view>
		</view>
		<!-- <view class="model-item">
			<image class="model-image" src="/static/img/icon3.png" mode="widthFix"></image>
			<view class="model-name">收益</view>
		</view> -->
		<view class="model-item" @click="goHomework">
			<image class="model-image" src="/static/img/icon3.png" mode="widthFix"></image>
			<view class="model-name">作业</view>
		</view>
		<view class="model-item" @click="goActivity">
			<image class="model-image" src="/static/img/icon4.png" mode="widthFix"></image>
			<view class="model-name">活动</view>
		</view>
	</view>
<!-- 	<video 	ref="videoPlayer"
			id="videoPlayer"
			loop
			autoplay
			is-live
			poster=""
			type="application/x-mpegURL"
			class="live-video"
			 src="https://player.xueqianban.vip/live/d11ce83c-d9aa-48dd-9021-a428f7fb9a65.flv?txSecret=e691ba78057b292d5f99b21c4468a2f6&txTime=687F0A42"></video> -->
	<view class="live-bg" v-if="live_list.length > 0 || course_list.length > 0">
		<view class="live-list">
			<view class="live-item-" v-for="(item, index) in courseLists" :key="item.id" @click="goCourses(item)">
				<!-- <image class="live-image" src="/static/img/pic.jpg" mode="widthFix"></image> -->
				<image class="live-image" :src="item.thumbnail" mode="aspectFill" v-if="item.status == 20"></image>
				<image class="live-image" :src="getImgUrl(item.thumbnail)" v-else mode="aspectFill"></image>
				<view class="live-title"><view>录播</view>：{{item.title}}</view>
				<!-- <view class="live-time">时间：{{ formatTime(item.last_time) }}</view> -->
				<view class="live-icon-play">
					<!-- <u-icon name="play-circle" size="70" :color="'#fff'"></u-icon> -->
					<image class="live-icon-image" src="/static/img/bfq-icon.png" mode="aspectFill"></image>
				</view>
				<view class="expire_time" v-if="item.isShowAirtime && item.expire_time > 0">
				    <u-icon name="lock" color="#12a15c" size="40" style="margin-bottom: 10rpx;margin-top: 12rpx;"></u-icon>
				    <u-count-down separator-size="26" color="#12a15c" :height="30" :timestamp="item.expire_time" @end="handleEnd2(index,item)"></u-count-down>
				</view>
			</view>
			<view class="live-item-" v-for="(item,index) in liveLists" :key="item.id" @click="goLive(item)">
				<!-- <image class="live-image" src="/static/img/pic.jpg" mode="widthFix"></image> -->
				<image class="live-image" :src="item.thumbnail" mode="aspectFill" v-if="item.status == 20"></image>
				<image class="live-image" :src="getImgUrl(item.thumbnail)" v-else mode="aspectFill"></image>
				<view class="live-tag">
					<u-tag :text="item.permission == 10 ? '所有人' : item.permission == 20 ? '会员' : '-'" mode="light" type="success" size="mini" />
				</view>
				<view class="live-title"><view>直播中</view>：{{item.title}}</view>
				<!-- <view class="live-time">时间：{{ formatTime(item.last_time) }}</view> -->
				<view class="time-item" v-if="item.isShowAirtime && item.countdown >= 0 && item.status == 40">
					<view>倒计时：</view>
					<u-count-down :timestamp="item.countdown" separator-size="26" color="#f50" :height="30" @end="handleEnd(index,item)"></u-count-down>
				</view>
				<view class="live-icon-play">
					<!-- <u-icon name="play-circle" size="70" :color="'#fff'"></u-icon> -->
					<image class="live-icon-image" src="/static/img/bfq-icon.png" mode="aspectFill"></image>
				</view>
			</view>
		</view>
		<!-- <view class="live-list" v-else>
			<view style="text-align: center;margin:auto">
				<image class="live-image" src="/static/empty.png" mode="aspectFill" style="width: 200rpx;height:200rpx;"></image>
				<view style="color: #999;font-size: 26rpx">暂无数据</view>
			</view>
		</view> -->
	</view>
	<view class="find-content">
		<mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ native: true }" @down="downCallback" :up="upOption"
		  @up="upCallback">
		  <!-- 视频朋友圈内容 -->
		  <view v-for="(item, index) in list.data" :key="index">
			  <view class="item uni-row">
			  	<image class="avatar" :src="item.user && item.user.avatar ? getImgUrl(item.user.avatar) : ''" mode="aspectFill" v-if="item.user && item.user.avatar && item.user.avatar != 'def-avatar.png'"></image>
				<image src="/static/def-avatar.png" class="avatar" mode="scaleToFill" v-else></image>
			  	<view class="content uni-row uni-column">
			  		<text class="name">{{ item.user.nick_name }}</text>
			  		<text class="text">{{ item.content }}</text>
			  		<!-- 图片 / 视频 -->
			  		<view class="images uni-row">
			  			<uni-moments-image :imageList="item.resources ? JSON.parse(item.resources) : []"></uni-moments-image>
			  		</view>
			  		<!-- 定位 -->
			  		<text class="address mt-5">{{ getJsonToObj(item.location) }}</text>
			  		<!-- 时间/点赞/评论按钮 -->
			  		<comment-line :scrollTop="scrollTop" :id="item.id" :userId="item.user_id" :createdAt="item.created_at"></comment-line>
			  		<!-- 点赞/评论信息列表 -->
			  		<comment :id="item.id" :isRefresh="isRefresh" :scrollTop="scrollTop"></comment>
			  	</view>
			  </view>
		  </view>
		</mescroll-body>
	</view>
	<!-- 点赞/评论 -->
	<comment-popup ref="commentPopup"></comment-popup>
	
	<!-- 点赞/评论 -->
	<comment-delete ref="commentDelete"></comment-delete>
	
	<!-- 评论输入框 -->
	<comment-input ref="commentInput"></comment-input>
	<!-- <kai-pengyouquan></kai-pengyouquan> -->
    <!-- 用户隐私保护提示（仅微信小程序） -->
    <!-- #ifdef MP-WEIXIN -->
    <PrivacyPopup :hideTabBar="true" />
    <!-- #endif -->
	
	<!-- <view id="mui-player2" style="height: 500rpx;"></view> -->

  </view>
</template>

<script>
  import { setCartTabBadge } from '@/core/app'
  import * as Api from '@/api/page'
  import Page from '@/components/page'
  import PrivacyPopup from '@/components/privacy-popup'
  // import kaiPengyouquan from '@/uni_modules/zenkuai/components/kai-pengyouquan/kai-pengyouquan.vue'
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
  import CommentPopup from './components/comment-popup.vue';
  import CommentDelete from './components/comment-delete.vue';
  import CommentLine from './components/comment-line.vue';
  import CommentInput from './components/comment-input.vue';
  import Comment from './components/comment.vue';
  import uniMomentsImage from '../../components/uni-moments-image/uni-moments-image.vue';
  import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
  import { timestampChangDate, ImgUrlPrefix } from '@/utils/util.js'
  import * as FindApi from '@/api/find'
  import * as LiveApi from '@/api/live'
  import * as homeworkApi from '@/api/homework'
  import store from '@/store/index.js'
  import { checkLogin } from '@/core/app'
  import storage from '@/utils/storage'
  import { STATUS } from '@/store/mutation-types'
  // import DPlayer from 'dplayer';
  // import 'mui-player/dist/mui-player.min.css'
  // import MuiPlayer from 'mui-player'
  // 每页记录数量
  const pageSize = 15
  export default {
	mixins: [MescrollMixin],
    components: {
      Page,
      PrivacyPopup,
	  // kaiPengyouquan,
	  CommentLine,
	  Comment,
	  CommentInput,
	  CommentPopup,
	  CommentDelete,
	  uniMomentsImage 
    },
    data() {
      return {
        // 页面参数
        options: {},
        // 页面属性
        page: {},
        // 页面元素
        items: [],
		// 上拉加载配置
		upOption: {
		  // 首次自动执行
		  auto: true,
		  // 每页数据的数量; 默认10
		  page: { size: pageSize },
		  // 数量要大于4条才显示无更多数据
		  noMoreSize: 4,
		  // 空布局
		  empty: {
		    tip: '亲，暂无帖子记录'
		  }
		},
		item_count: 20,
		listViewElement: null,
		refresherTriggered: false,
		refresherStyle: "none",
		text: `uni-app x，是下一代 uni-app，是一个跨平台应用开发引擎。uts是一门类ts的、跨平台的、新语言。uts在iOS端编译为swift、在Android端编译为kotlin、在Web端编译为js。`,
		imageList: [
			// "https://img1.baidu.com/it/u=1965663592,580944689&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1713286800&t=5c73d7f8aaa2a6f5114e659dd64e769d",
			// "https://img0.baidu.com/it/u=3838093562,4126749835&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1713286800&t=a2cd3d4ac8c0f2024a348772577a9d0f",
			// "https://img0.baidu.com/it/u=256816879,771155532&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1713286800&t=d5230b0cfdae75de3c452d973d302106",
		],
		list: getEmptyPaginateObj(),
		scrollTop: 0,
		keyboardHeight: 200, // ios 默认键盘高度，这里占位
		dataInfo: {
			commentList: [{toName:'',fromName:'查理斯', content:'这是什么地方？真好看啊'}] //评论列表
		},
		isRefresh:0,
		live_list: [], // 直播列表
		course_list: [], // 课程列表
		banner_list: [
		 //  {
			// image: "/static/img/banner.jpg",
			// title: "昨夜星辰昨夜风，画楼西畔桂堂东",
		 //  },
		],//baner列表
		airtime: -1, // 倒计时间
		isShowAirtime: true, // 是否显示倒计时间
		// 是否已登录
		isLogin: false,
      }
    },
	onReady() {
		// this.listViewElement = uni.getElementById('listview');
		this.listViewElement = uni.createSelectorQuery().in(this).select('#listview');
		// 监听点击评论事件
		uni.$on('commentScrollEvent', (y) => {this.listViewScrollByY(y.top - this.keyboardHeight + 40);this.isRefresh=0});
		// 监听一次键盘高度回调
		uni.$once('keyboardHeightEvent', (keyboardHeight) => {
			this.keyboardHeight = keyboardHeight;
		});
		// 监听评论回复回调
		uni.$on('commentSubmitEvent', (val) => {
			console.log('find评论回复内容',val)
			this.isRefresh = val.posts_id
		});
		uni.$on('RefreshList', (val) => {
			this.upCallback(1)
		})
	},
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
      // 当前页面参数
      this.options = options
	  this.getLiveList() // 直播列表
	  this.getCourseList() // 课程列表
	  this.getbannerList() // 轮播列表
	  // this.videoContext = uni.createVideoContext('videoPlayer');//创建视频实例指向video
	  // this.videoContext.play();  // 播放
	  // 判断是否已登录
	  this.isLogin = checkLogin()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      // 更新购物车角标
      setCartTabBadge()
    },
    mounted() {
		
		// const dp = new DPlayer({
		//     container: document.getElementById('dplayer'),
		//     video: {
		//         url: 'https://video.shipin520.com/videos/files/default/20230422/20/52/01/da032449a297193c9cc4acac01949e18_v1.mp4',
		//     },
		// });
		// var mp = new MuiPlayer({
		//     container:'#mui-player2',
		//     title:'标题',
		// 	live: true,
		//     src:'https://player.xueqianban.vip/live/3f6aa66c-822c-4b82-aada-176755c99788.m3u8?txSecret=d7fbeaadd538d3a22a74d773d3491263&txTime=6881A5B6',
		// })
	},
	computed:{
		liveLists() {
		  return this.live_list.map(item => {
			   return { ...item, countdown: item.status_at ? this.get_expire_time(item.status_at) : -1, isShowAirtime: true }
		  })
		},
		courseLists() {
		   return this.course_list.map(item => {
		 	   return { ...item, expire_time: item.expire_time ? this.get_expire_time(item.expire_time) : -1, isShowAirtime: true }
		   })
		}
	},
    methods: {
      /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
	    console.log(page, store.getters.userId)
        const app = this
		// https://doc.dcloud.net.cn/uni-app-x/component/#methods
		this.$refs['commentPopup'].hideCommentPopup(); // 隐藏点赞/评论
		this.$refs['commentDelete'].hideCommentPopup(); // 隐藏删除
		this.$refs['commentInput'].hideKeyboard(); // 隐藏评论框与键盘
        // 设置列表数据
        app.getPostsList(page.num)
          .then(list => {
			  console.log(list,'listlistlist')
            const curPageLen = list.items.length
            const totalSize = list.total
            app.mescroll.endBySize(curPageLen, totalSize)
          })
          .catch(() => app.mescroll.endErr())
      },
	  // 获取帖子列表
	  getPostsList(pageNo = 1) {
	    const app = this
	    return new Promise((resolve, reject) => {
	      FindApi.postsList({ 
			  page: pageNo,
              "user_id": store.getters.userId, // 默认 0，查看别人主页就是 用户id
	        }, { load: false })
	        .then(result => {
	          // 合并新数据
	          const newList = result.data
			  console.log('getMoreListDatagetMoreListDatagetMoreListData', getMoreListData(newList, app.list, pageNo))
	          app.list.data = getMoreListData(newList, app.list, pageNo)
	          resolve(newList)
	        })
	    })
	  },
	  // 转换json数据
	  getJsonToObj: function(val) {
	  	if(val) {
	  		let data = JSON.parse(val)
	  		if(data !== '{}') {
	  			return data.name
	  		} else {
	  			return ''
	  		}
	  	}else {
	  		return ''
	  	}
	  },
	  listViewScrollByY(y) {
		this.listViewElement.boundingClientRect((rect) => {
		  if (rect) {
		    uni.pageScrollTo({
		      scrollTop: y, // 滚动到目标元素的顶部
		      duration: 300, // 滚动动画的时长
		    });
		  }
		}).exec();
	  },
      /**
       * 设置顶部导航栏
       */
      setPageBar() {
        const { page } = this
        // 设置页面标题
        uni.setNavigationBarTitle({
          title: page.params.title
        })
        // 设置navbar标题、颜色
        uni.setNavigationBarColor({
          frontColor: page.style.titleTextColor === 'white' ? '#ffffff' : '#000000',
          backgroundColor: page.style.titleBackgroundColor
        })
      },
	  
	  // 直播列表
	  getLiveList() {
		const app = this
	  	LiveApi.liveList({ page: 1}).then(result => {
			// let array = [{
			// 	id: 1, 
			// 	thumbnail: '/static/img/live_img.png',
			// 	title: '三维游戏场景手绘课程第二节',
			// 	status: 20,
			// 	permission: 10
			// },
			// {
			// 	id: 2, 
			// 	thumbnail: '/static/img/live_img2.jpg',
			// 	title: '水墨风格手绘课程刘老师教学',
			// 	status: 20,
			// 	permission: 10
			// },
			// {
			// 	id: 3, 
			// 	thumbnail: '/static/img/live_img3.png',
			// 	title: '影视CG手绘课程张老师第6节课',
			// 	status: 20,
			// 	permission: 10
			// },
			// {
			// 	id: 4, 
			// 	thumbnail: '/static/img/live_img4.png',
			// 	title: '汽车模型手绘课程三',
			// 	status: 20,
			// 	permission: 10
			// }]
			// let array = []
			if(result.data.items.length> 0){
				// app.live_list = [...array, ...result.data.items]
				app.live_list = result.data.items
			} else {
				// app.live_list = [...array]
			}
	    }).catch(() => {
			
		})
	  },
	  
	  // 课程列表
	  getCourseList(pageNo =1) {
	  		const app = this
	  		FindApi.courseList({ page: pageNo }, { load: false })
			.then(result => {
				if(result.data.items.length > 0) {
					app.course_list = result.data.items.filter((item,index) => index < 4)
				} else {
					app.course_list = []
				}
			  
			})
	  },
	  // 轮播列表
	  getbannerList: function() {
	    const app = this
		Api.bannerList().then(result => {
			result.data.forEach(item => {
				item.thumbnail = app.getImgUrl(item.thumbnail)
			})
			app.banner_list = result.data
			console.log('轮播列表',result, app.banner_list)
	    }).catch(() => {
			
		})
	  },
	  // 轮播详情
	  goDetails: function(index) {
		  console.log('index', index)
		  let id = this.banner_list[index].id
		  this.$navTo('pages/index/bannerDetails', { id })
	  },
	  // 转换时间戳
	  formatTime (data) {
	  	const currTime = timestampChangDate('YYYY-mm-dd', data * 1000)
		return currTime
	  },
	  // 图片地址拼接
	  getImgUrl(val) {
		  const url = ImgUrlPrefix(val)
		  return url
	  },
	  //课程
	  goCourse() {
		  this.$navTo('pages/course/index')
	  },
	  goSquare() {
		  this.$navTo('pages/find/index')
	  },
	  // 去作业
	  goHomework() {
		  // this.$navTo('pages/user/homework/index')
		  if(!this.isLogin) {
		  	  homeworkApi.homeworkList({ page: 1 }, { load: false }).then(result => {})
		  } else {
			  let status = storage.get(STATUS)
			  if(this.get_expire_time(status) > 0) {
				this.$navTo('pages/user/homework/index')
			  } else {
				this.$toast('会员权限已过期')
			  }
		  }
	  },
	  // 活动
	  goActivity() {
		   // this.$navTo('pages/openClass/index', {id: 100009}) 
	  },
	  // 跳转直播页
	  goLive(val) {
		  console.log(val,'val')
	      this.$navTo('pages/live/liveStreaming',  { id:val.id, thumbnail: val.thumbnail })
	  },
	  // 跳转课程详情页
	  goCourses(val){
		  const app = this
		  if(val.expire_time <= 0){
		  	 this.$navTo('pages/course/course', { id: val.id, name: val.title, thumbnail: val.thumbnail })
		  } else {
		  	app.$toast('锁定状态无法进入')
		  }
	  },
	  get_expire_time: function(val) {
		const date = new Date().getTime();
		if(val && val != '') {
			let time = val * 1000 - date
			console.log(date,time)
			return time
		} else {
			return -1
		}
	  },
	  // 倒计时结束事件
	  handleEnd(index,val) {
	  	  console.log('倒计时结束')
		  this.isShowAirtime = false
		  this.live_list[index].isShowAirtime = false
	  },
	  // 课程倒计时结束事件
	  handleEnd2(index, val) {
		   console.log('倒计时结束')
		   this.course_list[index].isShowAirtime = false
	  },
    },

    /**
     * 下拉刷新
     */
    onPullDownRefresh() {
		console.log('下拉刷新')
      // 获取首页数据
	  this.live_list = []
      this.getLiveList()
	  this.getbannerList()
	  uni.stopPullDownRefresh()
    },

    /**
     * 分享当前页面
     */
    onShareAppMessage() {
      const app = this
      const { page } = app
      return {
        title: page.params.shareTitle,
        path: "/pages/index/index?" + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      const { page } = app
      return {
        title: page.params.shareTitle,
        path: "/pages/index/index?" + app.$getShareUrlParams()
      }
    },
	// 页面滚动时会被触发 ，获取滚动的高度
	onPageScroll(e) {
	  // 在这里编写滚动相关的逻辑
	  this.scrollTop = e.scrollTop;
	},

  }
</script>

<style lang="scss" scoped>
		@import '../find/index.scss';
  .container {
    background: #fff;
  }
  .top-log{
	  width: 100%;
	  position: relative;
	  // position: fixed;
	  // z-index: 2222;
	  .image{
		   width: 100%;
	  }
	  .yun-cloud{
		  width: 100%;
		  position: absolute;
		  bottom: -10rpx;
		  z-index: 1;
	  }
	  .image-cloud{
		  width: 100%;
	  }
  }
  .model-content-box{
	  display: flex;
	  justify-content: space-between;
	  padding: 20rpx 40rpx;
	  // padding-top: 434rpx;
	  .model-item{
		  width: 110rpx;
		  .model-image{
			  width: 100%;
			  border-radius: 50%;
		  }
		  .model-name{
			  text-align: center;
		  }
	  }
  }
  .live-bg{
	  background-color: #f3f7f8;
	  padding: 16rpx 0;
	  .live-list{
	  	  display: flex;
	  	  flex-wrap: wrap;
	  	  justify-content: space-between;
	  	  padding: 30rpx 40rpx;
		  background-color: #fff;
	  	  .live-item-{
	  		  max-width: 48%;
	  		  flex: 0 0 50%;
	  		  color: #666;
	  		  line-height: 54rpx;
			  position: relative;
			  border-radius: 16rpx;
			  margin-bottom: 20rpx;
	  		  .live-image{
	  			  width: 100%;
				  max-height: 176rpx;
	  			  border-radius: 20rpx;
				  background-color: #eef0f5;
	  		  }
			  .live-tag{
				  position: absolute;
				  top: 6rpx;
				  left:16rpx;
			  }
	  		  .live-title{
	  			  color: #12a15c;
				  display: flex;
				  overflow: hidden;
				  text-overflow: ellipsis;
				  white-space: nowrap;
	  		  }
	  		  .live-time{
	  			  
	  		  }
	  		  .live-address{
	  			  white-space: nowrap;
	  			  overflow: hidden;
	  			  text-overflow: ellipsis;
	  		  }
			  .live-icon-play{
				  position: absolute;
				  top: 0;
				  left:0;
				  width: 100%;
				  height: 70%;
				  line-height: 226rpx;
				  text-align: center;
				  border-radius: 20rpx;
				  // background-color: rgba(255,255,255,0.2);
				  .live-icon-image{
					  width: 80rpx;
					  height: 80rpx;
					  text-align: center;
					  opacity: 0.4;
				  }
			  }
			  .expire_time{
				  position: absolute;
				  top: 0;
				  width: 100%;
				  height: 71%;
				  text-align: center;
				  padding-top: 18rpx;
				  border-radius: 16rpx;
				  color: #12a15c;
				  background-color: rgba(0,0,0,0.5);
			  }
			  .time-item{
			  		 // background-color: rgba(0,0,0,0.95);
			  		 position: absolute;
			  		 bottom: 70rpx;
			  		 left: 0;
			  		 width:100%;
			  		 // height: 70%;
			  		 text-align: center;
			  		 color:  #f50;
			  		 // padding-top: 68rpx;
			  		 // line-height: 48rpx;
			  		 // font-size: 30rpx;
			  		border-radius: 20rpx;
					display: flex;
					align-items: flex-end;
					justify-content: center;
					font-size: 26rpx;
			  }
	  	  }
	  }
  }
  .find-content{
	 padding: 20rpx 0rpx; 
  }
  
</style>